<?php

namespace app\link\logic;

use app\common\logic\Base;
use think\facade\App;
use think\facade\Request;

class Index extends  Base {
    
    /**
     * @desc 短链跳转
     * @rule 链接类型
     *  0.普通链接
     *  1.时间链接 【设置链接的访问时效】
     *  2.私密链接 【设置访问密码】
     *  3.次数链接 【设置访问次数】
     * @param $keyword
     * @return array|bool
     * @throws \Exception
     */
    public function redirect($keyword) {
        $request= Request::instance();
        $ip = $request->ip(); //获取客户端IP地址
        $currentDomain = $request->domain();  //获取当前包含协议、端口的域名
        $currentUrl = $request->url(); //获取当前完整URL 包括QUERY_STRING
        $header = $request->header();
        $userAgent = $header['user-agent'];
        
        $urlInfo = model('Url')->where('keyword', '=', $keyword)->find();
        if(!$urlInfo) {
            return url('index/shortError',['tips' => urlencode('该访问链接不存在')]);
        }
    
        //跳转链接
        $redirectUrl = $urlInfo['link'];
        
        //判断是注册用户还是普通访客
        if($urlInfo['user_id']) {
            switch ($urlInfo['link_type']) {
                case 1: { //时间链接
                    if($urlInfo['expire_time'] < date('Y-m-d H:i:s')){
                        $redirectUrl = url('index/shortError', ['tips' => urlencode('访问链接已失效')]);
                    }
                    break;
                }
                case 2: { //私密链接
                    if($urlInfo['password']){
                        $redirectUrl = url('index/password', ['keyword' => $keyword]);
                    }
                    break;
                }
            }

            //查看当前urlId关联了哪些渠道并计数
            $channelIds = model('UrlChannelRelation')
                ->where('ucr_url_id', '=', $urlInfo['url_id'])
                ->column('ucr_channel_id');
            if($channelIds) {
                foreach ($channelIds as $v) {
                    @model('UrlChannel')->where('uc_channel_id', '=', $v)->setInc('uc_clicks');
                }
            }

            //如果没有检测到http协议就加上域名和keyword关键词
            //if(strpos($urlInfo['link'],'http://') === false || strpos($urlInfo['link'],'https://') === false){
                //短链接地址
                //$domainUrl = model('Domain')->getDomain($urlInfo['user_id']);
                //$redirectUrl = $domainUrl.'/'.$urlInfo['keyword'];
            //}

        //普通访客 限定访问30次数和访问3天数
        }else {
            if($urlInfo['expire_time'] < date('Y-m-d H:i:s')){
                $redirectUrl = url('index/shortError',['tips' => urlencode('访问链接已过有效期')]);
            }
            
            //记录访问次数
            if($urlInfo['clicks'] >= $urlInfo['limit_clicks']){
                $redirectUrl = url('index/shortError',['tips' => urlencode('访问链接已失效')]);
            }
        }

        //访问次数+1
        model('Url')->where('url_id', '=', $urlInfo['url_id'])->setInc('clicks');

        /**
         * 解析原始地址
         * 完整链接：http://aa.abc.com/download/v3?agentCode=55421603&channelCode=android
         * array() {
         *    "scheme"=> "http"
         *    "host"  => "aa.abc.com"
         *    "path"  => "/download/v3"
         *    "query" => "agentCode=55421603&channelCode=android"
         * }
         */
        $fullUrl = $currentDomain . $currentUrl;
        $parseInfo = parse_url($fullUrl);
        @model('UrlLog')->insert([
            'url_id'      => $urlInfo['url_id'],
            'short_url'   => $currentDomain . '/' . $urlInfo['keyword'],
            'full_url'    => $fullUrl,
            'link_scheme' => $parseInfo['scheme'] ?: '',
            'link_host'   => $parseInfo['host'] ?: '',
            'link_path'   => $parseInfo['path'] ?: '',
            'link_query'  => $parseInfo['query'] ?: '',
            'user_agent'  => $userAgent,
            'ip'          => $ip,
            'click_time'  => date('Y-m-d H:i:s'),
            'create_time' => date('Y-m-d H:i:s')
        ]);
        return $redirectUrl;
    }
    
    /**
     * @desc 检查密码
     * @param string $keyword 短链关键词
     * @param string $password 短链密码
     * @return array|bool
     * @throws \Exception
     */
    public function checkPassword($keyword,$password) {
        $urlInfo = model('Url')->where('keyword', '=', $keyword)->find();
        if(!$urlInfo) {
            $this->errorCode = EC_LINK_URL_NOT_EXIST;
            return false;
        }
        
        if(!$urlInfo['password']) {
            $this->errorCode = EC_LINK_EMPTY_PASSWORD;
            return false;
        }
        
        if($urlInfo['password'] != $password) {
            $this->errorCode = EC_LINK_PASSWORD_ERROR;
            return false;
        }
        return [
            'link' => $urlInfo['link']
        ];
    }
}
